package com.levy.contronller.javase.nio;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * Created by levy on 2018/7/31.
 */
public class MyFixSizeThreadPool {


    //仓库
    private BlockingQueue<Runnable> taskQueue;

    //工作线程
    private List<Worker> workers;

    //线程池的工作标识  volatile 当改变了变量的值的时候 其他线程获取到的值会成为最新改变后的值 保持同步
    private volatile boolean working = true;


    public MyFixSizeThreadPool(int poolSize, int taskQueSize) {
        if (poolSize <= 0 || taskQueSize <= 0) {
            throw new IllegalArgumentException("参数错误");
        }

        this.taskQueue = new LinkedBlockingDeque<>(poolSize);
        //初始化线程
        //可变的线程池  xiancheng安全
        this.workers = Collections.synchronizedList(new ArrayList<Worker>());
        for (int i = 0; i < poolSize; i++) {
            Worker worker = new Worker(this);
            worker.start();
            this.workers.add(worker);
        }
    }

    //放入任务方法
    public boolean submit(Runnable task) {
        if (this.working) {
            //注意使用的方法
            return this.taskQueue.offer(task);
        } else {
            return false;
        }
    }


    //关闭方法
    public void shutdown() {
        this.working = false;
        //中断  正在阻塞中的线程
        for (Thread t : this.workers) {
            //判断线程状态是否为阻塞状态
            Thread.State state = t.getState();
            if (state.equals(Thread.State.BLOCKED)
                    || state.equals(Thread.State.TIMED_WAITING)
                    || state.equals(Thread.State.WAITING)){
                //唤醒  中断
                t.interrupt();
            }


        }

    }


    private static class Worker extends Thread {

        private MyFixSizeThreadPool pool;

        public Worker(MyFixSizeThreadPool pool) {
            this.pool = pool;
        }

        @Override
        public void run() {
            //测试效果  执行的任务量
            int taskCount = 0;
            while (this.pool.working || this.pool.taskQueue.size() > 0) {
                Runnable task = null;

                //获取线程
                try {
                    //当队列中有任务的时候 ，池已经关闭时
                    if (this.pool.working) {
                        //当没任务的时候  调用take  会在阻塞状态   这时候 外面有人shutdown的时候  会导致线程池无法关闭
                        //不用take的话  需要自己去做唤醒 等待
                        task = this.pool.taskQueue.take();
                    } else {
                        task = this.pool.taskQueue.poll();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //运行
                if (task != null) {
                    task.run();
                    System.out.println(Thread.currentThread().getName() + "执行完" + (++taskCount) + "个");
                }

            }
            System.out.println(Thread.currentThread().getName() + "结束");

        }


    }


    public static void main(String[] args) {
        MyFixSizeThreadPool pool = new MyFixSizeThreadPool(3, 6);
        for (int i = 0; i < 6; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行中……");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        pool.shutdown();


    }

}
